const express = require('express');

// 实体类
const ObjId = require('../entity/common/ObjId');
const Response = require('../entity/http/Response');

// 业务层
const cityService = require('../service/city');

const router = express.Router();

/**
 * @apiName 获取所有省份接口
 */
router.get('/province', function (req, res, next) {
    console.log(`[ REQUEST ] [ req-id = ${ req.requestId } ] [ Controller ] 请求进入 GET /city/province`);
    cityService.getAllProvince(req.requestId).then(result => {
        console.log(`[ RESPONSE ] [ req-id = ${ req.requestId } ] [ Controller ] 查询所有省份响应 ${ JSON.stringify(result) }`);
        return res.status(result.code).json(result);
    }).catch(err => {
        console.log(`[ ERROR ] [ req-id = ${ req.requestId } ] [ Controller ] 查询所有省份时服务器内部错误 ${ err.message }`);
        return res.status(500).json(new Response().fail(500, '服务器内部错误'));
    });
});

/**
 * @apiName 获取某个省份下所有城市
 * @param { int }   id   省份ID - 主键
 */
router.get('/citys', function (req, res, next) {
    console.log(`[ REQUEST ] [ req-id = ${ req.requestId } ] [ Controller ] 请求进入 GET /city/citys`);
    let province;
    try {
        province = new ObjId(req.query.id);
    } catch (err) {
        return res.status(400).json(new Response().fail(400, "省份Id有误"));
    }
    console.log(`[ INFO ] [ req-id = ${ req.requestId } ] [ Controller ] 省份参数 ${ JSON.stringify(province) }`);
    cityService.getCitysByProvinceId(req.requestId, province.id).then(result => {
        console.log(`[ RESPONSE ] [ req-id = ${ req.requestId } ] [ Controller ] 查询省份下所有城市响应 ${ JSON.stringify(result) }`);
        return res.status(result.code).json(result);
    }).catch(err => {
        console.log(`[ ERROR ] [ req-id = ${ req.requestId } ] [ Controller ] 查询省份下所有城市时服务器内部错误 ${ err.message }`);
        return res.status(500).json(new Response().fail(500, '服务器内部错误'));
    });
});

module.exports = router;